﻿/**************************************************************************
创建时间:	2021/1/24 12:21:09    
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcun.cn

描	述：
记	录：
***************************************************************************/
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ZhCun.DbCore.Cores;
using ZhCun.DBModel;
using ZhCun.Utils;
using ZhCun.WebUtils.Configs;
using ZhCun.WebUtils.DB;

namespace ZhCun.WebUtils
{
    //不使用该过滤器，使用 LogFilterAttribute
    public class HttpLogMiddleware
    {
        static HttpLogMiddleware()
        {
            RunToDBTask();
        }

        private readonly RequestDelegate _next;

        //Stopwatch stopwatch;

        public HttpLogMiddleware(RequestDelegate next)
        {
            this._next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            //stopwatch = new Stopwatch();
            //stopwatch.Start();//在下一个中间价处理前，启动计时器

            var m = new Log_Http
            {
                Path = context.Request.Path,
                //Interval = (int)stopwatch.ElapsedMilliseconds,
                AddHost = context.Connection.RemoteIpAddress.ToString(),
                RepStatus = context.Response.StatusCode,
                LogTime = DateTime.Now,
                ReqLength = (int)(context.Request.ContentLength ?? 0),
                ReqMethod = context.Request.Method,

            };



            await _next.Invoke(context);

            context.Response.OnCompleted(() => 
            {
                m.Interval = (int)(DateTime.Now - m.LogTime).TotalMilliseconds;
                m.RepLength = (int)(context.Response.ContentLength ?? -1);
                AddLog(m);
                return Task.CompletedTask;
            });
        }

        static Queue<Log_Http> LogQueues { get; } = new Queue<Log_Http>();

        void AddLog(Log_Http model)
        {
            LogQueues.Enqueue(model);
        }

        static void RunToDBTask()
        {
            if (!CommonConfig.THIS.LogHttpSave) return;
            Task.Run(ToDBTask);
            void ToDBTask()
            {
                var log = LogHelper.CreateLog("LogHttp");
                //DBMain db = new DBMain(CommonConfig.THIS.LogDbConnStr);
                //var logDbType = DBContext.GetDbType(CommonConfig.THIS.LogDbType);
                var db = new DBContextDebug(DBMain.DBType, CommonConfig.THIS.LogDbConnStr);
                log.Info("开始Http日志保存任务");
                while (true)
                {
                    try
                    {
                        if (LogQueues.Count > 0)
                        {
                            var m = LogQueues.Dequeue();
                            if (m == null) continue;
                            db.Insert(m);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("保存 http log 出错", ex);
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(10));
                }
            }
        }
    }
}
